<?php
/**
 * User: 苏翔
 * Date: 2024/8/16 14:07
 */

namespace App\Dao;

use App\HscoinConf;
use App\Model\HscoinBalanceModel;
use App\Model\HscoinBillModel;
use App\Model\PriceHourlyModel;
use App\Model\PriceLogModel;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class PriceHourlyDao extends BaseDao
{

    #[Inject]
    protected PriceHourlyModel $model;
    #[Inject]
    protected PriceLogModel $logModel;


    function getList($uid = 0, $category = 0, $min_id = 0, $max_id = 0, $size = 10): array
    {
        $size = max(1, (int)$size);
        $where = compact('uid', 'category');
        $where = array_filter($where);
        $orderDirection = 'desc';
        if ($min_id) {
            $where[] = ['id', '>', $min_id];
            $orderDirection = 'asc';
        } elseif ($max_id) {
            $where[] = ['id', '<', $max_id];
        }
        return $this->model->where($where)->orderBy('id', $orderDirection)->limit($size)->get()->toArray();
    }


    function lastLog($time_key): array
    {
        $add_time = strtotime($time_key);
        // 读id最大一条，add_time<$add_time
        $rs = $this->logModel->where('add_time', '<', $add_time)->orderBy('id', 'desc')->first();
        return $rs ? $rs->toArray() : [];
    }

    function exist($key)
    {
        return $this->model->where('key_time', $key)->value('id');
    }

    function getOpen()
    {

    }

    function handle($time_key)
    {
        if ($this->exist($time_key)) {
            return true;
        }

        $lastLog = $this->lastLog($time_key);
        if (!$lastLog) {
            return false;
        }

        $price = $lastLog['price'] ?? 0;
        if (!($price > 0)) {
            return false;
        }


        $open = $price;
        if ($lastClose = $this->lastClose()) {
            $open = $lastClose;
        }

        $data = [
            'key_time' => $time_key,
            'close' => $price,
            'open' => $open,
            'add_time' => time(),
        ];

        return $this->model->insertGetId($data);
    }

    function lastClose()
    {
        return (float)$this->model->orderBy('id', 'desc')->value('close');
    }
}
